package cn.zn.modules.money.cur.controller;

import cn.zn.framework.common.utils.R;
import cn.zn.framework.common.vo.CodeNameVO;
import cn.zn.modules.money.cur.entity.TMoneyInfo;
import cn.zn.modules.money.cur.entity.vo.MoneyAvailableProjectVO;
import cn.zn.modules.money.cur.service.TMoneyInfoService;
import cn.zn.modules.zzsys.inter.SysDicInter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("money/cur/moneyinfo")
@Slf4j
public class TMoneyInfoController {

    @Autowired
    private TMoneyInfoService tMoneyInfoService;
    @Autowired
    private SysDicInter sysDicInter;

    /**
     * 可用金额
     *
     * @param projectCode
     * @return
     */
    @GetMapping("/queryAvailableMoney/{projectCode}/{cateCode}")
    public R queryAvailableMoney(@PathVariable String projectCode, @PathVariable String cateCode) {
        return R.ok().put("money", tMoneyInfoService.queryAvailableMoney(projectCode, cateCode).getAvailableMoney());
    }

    /**
     * 可用项目
     *
     * @return
     */
    @GetMapping("/queryAvailableProjects")
    public R queryAvailableProjects() {
        return R.ok().put("projects", tMoneyInfoService.queryAvailableProjects()
                .stream()
                .collect(Collectors.toMap(MoneyAvailableProjectVO::getProjectCode, o -> o.getProjectName(), (o1, o2) -> o1, LinkedHashMap::new)));
    }

    /**
     * 可用经济分类
     *
     * @param projectCode
     * @return
     */
    @GetMapping("/queryAvailableCates/{projectCode}")
    public R queryAvailableCates(@PathVariable String projectCode) {
        return R.ok().put("cates", this.getBootstrapTreeNodesCate(tMoneyInfoService.queryAvailableCates(projectCode).stream().map(o -> o.getCateCode()).collect(Collectors.toSet()), null));
    }

    @GetMapping("/querySum")
    public R querySum() {
        return R.ok().put("sum", tMoneyInfoService.querySum());
    }

    @PostMapping("querySumDetail")
    public R querySumDetail(@RequestBody TMoneyInfo tMoneyInfo) {
        return R.ok().put("sumDetail", tMoneyInfoService.querySumDetail(tMoneyInfo));
    }

    @PostMapping("querySuspended/{id}")
    public R querySuspended(@PathVariable String id) {
        return R.ok().put("list", tMoneyInfoService.querySuspended(id));
    }

    @PostMapping("saveSuspended")
    public R saveSuspended(@RequestBody TMoneyInfo tMoneyInfo) {
        tMoneyInfoService.saveSuspended(tMoneyInfo);
        return R.ok();
    }

    @DeleteMapping
    public R delete(@RequestBody String[] ids) {
        tMoneyInfoService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

    /**
     * 将可用经济分类整理为树型
     *
     * @param cateList
     * @param expanded
     * @return
     */
    private Set<Map<String, Object>> getBootstrapTreeNodesCate(Set<String> cateList, Boolean expanded) {
        // 获取所有经济分类
        Map<String, String> cateMap = sysDicInter.querySysDicDatas("jjfl").stream().collect(Collectors.toMap(CodeNameVO::getCode, o -> o.getName(), (o1, o2) -> o1, LinkedHashMap::new));
        Set<Map<String, Object>> set = new LinkedHashSet<>();
        Map<String, Object> map = null;
        Map<String, Object> state = new HashMap<>();
        state.put("expanded", expanded == null ? true : expanded);
        if (cateList != null && cateList.size() > 0) {// 获得指定节点
            String keyBig = "";
            Boolean existBig = false;
            Map<String, Object> mapBig = null;
            HashSet<Map<String, Object>> nodes = null;
            Set<String> keys = cateMap.keySet();
            for (String cateCode : cateList) {
                // 判断要添加的类型是大类还是小类
                // 大类：将其下所有小类添加到子集合中
                // 小类：查找到对应的大类，并将自己添加到子集合中
                if (cateCode.length() == 3) {// 大类
                    keyBig = cateCode;
                    existBig = false;
                    for (Map<String, Object> setItem : set) {
                        if (setItem.get("id").equals(cateCode)) {
                            existBig = true;
                            mapBig = setItem;
                            break;
                        }
                    }
                    if (!existBig) {
                        mapBig = new HashMap<>();
                        mapBig.put("id", keyBig);
                        mapBig.put("code", keyBig);
                        mapBig.put("text", keyBig.concat(" ").concat(cateMap.get(keyBig)));
                        mapBig.put("state", state);
                        mapBig.put("nodes", new LinkedHashSet<>());
                        set.add(mapBig);
                    }
                    for (String key : keys) {
                        if (key.length() > 3 && key.substring(0, 3).equals(keyBig)) {
                            map = new HashMap<>();
                            map.put("id", key);
                            map.put("code", key);
                            map.put("text", key.concat(" ").concat(cateMap.get(key)));
                            map.put("state", state);
                            ((Set<Map<String, Object>>) mapBig.get("nodes")).add(map);
                        }
                    }
                } else {// 小类
                    keyBig = cateCode.substring(0, 3);
                    existBig = false;
                    for (Map<String, Object> setItem : set) {
                        if (setItem.get("id").equals(cateCode.substring(0, 3))) {
                            existBig = true;
                            mapBig = setItem;
                            break;
                        }
                    }
                    // 小类
                    map = new HashMap<>();
                    map.put("id", cateCode);
                    map.put("code", cateCode);
                    map.put("text", cateCode.concat(" ").concat(cateMap.get(cateCode)));
                    map.put("state", state);
                    if (existBig) {// 返回集合中存在
                        ((Set<Map<String, Object>>) mapBig.get("nodes")).add(map);
                    } else {
                        // 大类
                        mapBig = new HashMap<>();
                        mapBig.put("id", keyBig);
                        mapBig.put("code", keyBig);
                        mapBig.put("text", keyBig.concat(" ").concat(cateMap.get(keyBig)));
                        mapBig.put("state", state);
                        nodes = new LinkedHashSet<>();
                        nodes.add(map);
                        mapBig.put("nodes", nodes);
                        set.add(mapBig);
                    }
                }
            }
        } else {// 整棵树
            Iterator<String> keyIt = cateMap.keySet().iterator();
            String key = "";
            while (keyIt.hasNext()) {
                key = keyIt.next();
                map = new HashMap<>();
                map.put("id", key);
                map.put("code", key);
                map.put("text", key.concat(" ").concat(cateMap.get(key)));
                map.put("state", state);
                if (key.length() == 3) {
                    set.add(map);
                } else {
                    for (Map<String, Object> setItem : set) {
                        if (setItem.get("id").equals(key.substring(0, 3))) {
                            if (setItem.get("nodes") == null) {
                                setItem.put("nodes", new LinkedHashSet<>());
                            }
                            ((Set<Map<String, Object>>) setItem.get("nodes")).add(map);
                        }
                    }
                }
            }
        }
        return set;
    }
}
